#!/usr/bin/python

"""Project Euler Solution 059

Copyright (c) 2011 by Robert Vella - robert.r.h.vella@gmail.com

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and / or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
"""

import cProfile
from itertools import product
from euler.list_functions import first
from euler.file_functions import split_file

def get_answer():    
    """Question:
    
    Each character on a computer is assigned a unique code and the preferred 
    standard is ASCII (American Standard Code for Information Interchange). For
    example, uppercase A = 65, asterisk (*) = 42, and lowercase k = 107.

    A modern encryption method is to take a text file, convert the bytes to 
    ASCII, then XOR each byte with a given value, taken from a secret key. The 
    advantage with the XOR function is that using the same encryption key on 
    the cipher text, restores the plain text; for example, 65 XOR 42 = 107, 
    then 107 XOR 42 = 65.
    
    For unbreakable encryption, the key is the same length as the plain text 
    message, and the key is made up of random bytes. The user would keep the 
    encrypted message and the encryption key in different locations, and 
    without both "halves", it is impossible to decrypt the message.
    
    Unfortunately, this method is impractical for most users, so the modified 
    method is to use a password as a key. If the password is shorter than the 
    message, which is likely, the key is repeated cyclically throughout the 
    message. The balance for this method is using a sufficiently long password 
    key for security, but short enough to be memorable.
    
    Your task has been made easy, as the encryption key consists of three 
    lower case characters. Using cipher1.txt 
    (right click and 'Save Link/Target As...'), 
    a file containing the encrypted ASCII codes, and the knowledge that the 
    plain text must contain common English words, decrypt the message and find 
    the sum of the ASCII values in the original text.
    """
    
    def decrypt(message, key):
        """Returns the decrypted version of [message] using [key] to decrypt 
        it.
        
        """        
        message_length = len(message)
        return (message[j] ^ key[j - i] 
                for i in range(0, message_length, 3) 
                for j in range(i, i + 3) 
                if j < message_length)
    
    def get_valid_key(encrypted_message_characters):
        """Returns the 3-lowercase-character key for which the decrypted 
        version of [encrypted_message_characters] only has ascii characters.
        """
        
        #All the keys made up of three lowercase characters.
        three_character_keys = product(
                                       range(97, 123),
                                       range(97, 123),
                                       range(97, 123)
                                    )
        
        def isvalid(key):
            """Returns true if the decrypted version of 
            encrypted_message_characters using [key] only has ascii characters.
            """
            
            return all(32 <= x <= 122 and x != 35 and x != 96
                       for x in decrypt(encrypted_message_characters, key))
        
        #Return the first 3-lowercase-character key which meets the criteria 
        #for validity.
        return first(key for key in three_character_keys if isvalid(key))
    
    #The encrypted characters in the message.    
    encrypted_message_characters = [int(char) for char 
                                        in split_file("../data/059.txt")]
    
    #The key used to decrypt the message.
    valid_key = get_valid_key(encrypted_message_characters)
    
    #The decrypted message.
    message = [decrypted_character 
                for decrypted_character 
                in decrypt(encrypted_message_characters, valid_key)]
    
    
    #Return result.
    return sum(i for i in message)


if __name__ == "__main__":
    cProfile.run("print(get_answer())")
